﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WatchMyToon
{
    class configloader
    {
        private string m_configfile = "";

        private Dictionary<string, string> configvalues = new Dictionary<string, string>();

        public configloader(string configFile)
        {
            this.m_configfile = configFile;
        }


        public bool fileExist()
        {
            return File.Exists(m_configfile);
        }

        public bool load()
        {
            if (fileExist())
            {
                string line;
                StreamReader file = null;
                try
                {
                    file = new StreamReader(m_configfile);
                    while ((line = file.ReadLine()) != null)
                    {
                        if (line.Contains("="))
                        {
                            string[] values = line.Split('=');
                            configvalues.Add(values[0], values[1]);
                        }
                    }
                }
                finally
                {
                    if (file != null)
                        file.Close();
                }


            }
            else
            {
                String directoryName = Path.GetDirectoryName(m_configfile);

                if (!Directory.Exists(directoryName))
                    Directory.CreateDirectory(directoryName);

                System.IO.StreamWriter file = new System.IO.StreamWriter(m_configfile);

            }
            return true;
        }

        public string get(string key)
        {
            if (configvalues.ContainsKey(key))
                return configvalues[key];
            else
                return string.Empty;
        }

        public void set(string key, string value)
        {
            if (configvalues.ContainsKey(key))
                configvalues[key] = value;
            else
                configvalues.Add(key, value);
        }


        public void removeSection(string key)
        {
            if (configvalues.ContainsKey(key))
                configvalues.Remove(key);
        }

        public void save()
        {
            if (fileExist())
                File.Delete(m_configfile);

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(m_configfile))
            {
                foreach (var entry in configvalues)
                {
                    file.WriteLine(entry.Key + "=" + entry.Value);
                }
            }
        }

    }
}
